const momentService = require('../service/moment.service')
const fileService = require('../service/file.service')
const fs = require('fs')
class MomentController {
  async create(ctx, next) {
    const userid = ctx.user.id
    const content = ctx.request.body.content
    // console.log(content,userid);
    const result = await momentService.create(userid, content)
    ctx.body = result
  }

  async detail(ctx, next) {
    const {momentId} = ctx.params
    const result = await momentService.getMomentId(momentId)
    ctx.body = result
  }

  async list(ctx, next) {
    const {offset, size} = ctx.query

    // console.log(offset);
    const result = await momentService.getMomentList(offset, size)
    ctx.body = result
  }

  async update(ctx, next) {
    const {momentId} = ctx.params
    const {content} = ctx.request.body

    const result =await  momentService.updateMoment(content,momentId)
    ctx.body = result
  }

  async remove(ctx, next){
    const {momentId} = ctx.params
    const result = await momentService.deleteMoments(momentId)
    ctx.body = result
  }
  async addLabels(ctx,next){
    const { labels } = ctx;
    const { momentId } = ctx.params;
    // console.log(labels[0].id,momentId)
    // 2.添加所有的标签
    for (let label of labels) {
      // 2.1.判断标签是否已经和动态有关系
      const isExist = await momentService.hasLabel(momentId, label.id);
      if (!isExist) {
        await momentService.addLabel(momentId, label.id);

      }
    }
    ctx.body = '嚯 你可真帅'
  }

  async fileInfo(ctx,next){

    let {filename } = ctx.params
    const fileInfo = await fileService.getFileInfo(filename)
    const { type } = ctx.query;
    const types = ["small", "middle", "large"];
    if (types.some(item => item === type)) {
      filename = filename + '-' + type;
    }
    ctx.response.set('content-type', fileInfo.mimetype)
    ctx.body= fs.createReadStream(`./uploads/picture/${filename}`)
  }
}

module.exports = new MomentController()